package com.okbihuo.perm.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.okbihuo.perm.core.auth.helper.AuthHelper;
import com.okbihuo.perm.core.tool.dict.YesOrNo;
import lombok.extern.java.Log;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 只能放到web项目里设置
 * 最后更新时间容易被自动更新的数据覆盖，似乎最好是自己写
 */
@Component
@Log
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasSetter("createdDate")) {
            this.fillStrategy(metaObject, "createdDate", System.currentTimeMillis());
        }
        if (metaObject.hasSetter("createdBy")) {
            this.fillStrategy(metaObject, "createdBy", AuthHelper.currentAwareUserId());
        }
//        if (metaObject.hasSetter("lastModifiedBy")) {
//            this.fillStrategy(metaObject, "lastModifiedBy", AuthHelper.currentAwareUserId());
//        }
//        if (metaObject.hasSetter("lastModifiedDate")) {
//            this.fillStrategy(metaObject, "lastModifiedDate", LocalDateTime.now());
//        }
        if (metaObject.hasSetter("del")) {
            this.fillStrategy(metaObject, "del", YesOrNo.NO.ordinal());
        }
        // revision自动从0开始
        if (metaObject.hasSetter("version")) {
            this.fillStrategy(metaObject, "version", 0);
        }
        // 如果没有特别设置则自动启用
        if (metaObject.hasSetter("enabled") && metaObject.getValue("enabled")==null) {
            this.fillStrategy(metaObject, "enabled", 1);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter("lastModifiedBy")) {
            this.fillStrategy(metaObject, "lastModifiedBy", AuthHelper.currentAwareUserId());
        }
        if (metaObject.hasSetter("lastModifiedDate")) {
            this.fillStrategy(metaObject, "lastModifiedDate", System.currentTimeMillis());
        }
    }
}
